package ct.zxd.utils;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.io.Reader;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

//定制Verifier
class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
  return true;
}
}

public class HttpsRequest {
	
	public static String sendGetRequest(String url, String postData) throws Exception {
	    
	    HttpsURLConnection conn = null;
	    OutputStream out = null;
	    String rsp = null;
	    byte[] byteArray = null;
	    if (postData != null) {
	    	byteArray = postData.getBytes("utf-8");
		}
	    
	    try {
	      URL uri = new URL(url);
	      conn = (HttpsURLConnection) uri.openConnection();
	    //忽略证书验证--Begin
	      conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
	    //忽略证书验证--End
	      conn.setRequestMethod("GET");
	      conn.setDoInput(true);
	      conn.setDoOutput(true);
	      conn.setRequestProperty("Host", uri.getHost());
	      conn.setRequestProperty("Content-Type", "application/json");
	      out = conn.getOutputStream();
	      if (postData != null) {
	    	  out.write(byteArray);
	      }
	      out.close();
	      if(conn.getResponseCode()==200) {
	        rsp = getStreamAsString(conn.getInputStream(), "utf-8");
	      }else {
	        rsp = getStreamAsString(conn.getErrorStream(), "utf-8");
	      }
	       
	      return rsp;
	 
	    } catch (Exception e) {
	      if(null!=out)
	        out.close();
	      e.printStackTrace();
	       
	    }
	    
	    return "获取用户信息失败";
	     
	  }
	   
	  /**
	   * getJson
	   * 
	   */
//	  private static String getJson() {
//	    return "{" + "\"name\"" + ":" + "\"robo_blogs_zh123\"" + "}";
//	  }
	 
	  private static String getStreamAsString(InputStream stream, String charset) throws IOException {
	    try {
	      Reader reader = new InputStreamReader(stream, charset);
	      StringBuilder response = new StringBuilder();
	 
	      final char[] buff = new char[1024];
	      int read = 0;
	      while ((read = reader.read(buff)) > 0) {
	        response.append(buff, 0, read);
	      }
	 
	      return response.toString();
	    } finally {
	      if (stream != null) {
	        stream.close();
	      }
	    }
	  }

}
